<template>
    <div class="header-nav">
        <el-header class="header-bar">
            <!-- Logo部分 -->
            <div class="logo-container">
                <img src="@/assets/images/logo.png" alt="logo" class="logo" />
            </div>

            <!-- 动态导航按钮 -->
            <div class="nav-links">
                <el-button v-for="item in navItems" :key="item.path" @click="navigateTo(item.path)" type="primary" link>
                    {{ item.label }}
                </el-button>
            </div>

            <!-- 用户信息部分 -->
            <div class="user-info">
                <span class="username">{{ userName }}</span>
                <el-button type="primary" link @click="logout">退出登录</el-button>
            </div>
        </el-header>
    </div>
</template>

<script setup>
import { computed } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '@/store/authStore'; // 引入 Pinia Store
import { ElMessage } from 'element-plus';

const router = useRouter();
const authStore = useAuthStore();

// 用户名（从 Pinia Store 中获取）
const userName = computed(() => authStore.username);

// 动态获取导航项
const navItems = computed(() => {
    const userRoute = router.options.routes.find((route) => route.path === '/user');
    if (!userRoute?.children) {
        console.error('未找到 /user 路由或其子路由');
        return [];
    }
    // 提取带有 meta.title 的子路由并返回对应的 label 和 path
    return userRoute.children
        .filter((child) => child.meta?.title)
        .map((child) => ({
            label: child.meta.title,
            path: `/user/${child.path}`,
        }));
});

// 路由跳转函数
const navigateTo = (path) => {
    router.push(path).catch((err) => {
        if (err.name !== 'NavigationDuplicated') console.error('路由跳转错误:', err);
    });
};

// 退出登录
const logout = () => {
    authStore.clearAuthData(); // 清理用户信息
    ElMessage.success('已成功退出登录');
    router.push('/login').catch((err) => console.error('退出登录跳转错误:', err));
};
</script>

<style scoped>
.header-nav {
    width: 100%;
    background-color: #2c3e50;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.header-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 70px;
    color: #fff;
}

.logo-container {
    display: flex;
    align-items: center;
}

.logo {
    width: 200px;
    margin-right: 20px;
}

.nav-links {
    display: flex;
    gap: 25px;
}

.nav-links .el-button {
    font-size: 16px;
    font-weight: 500;
    color: #fff;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 20px;
}

.username {
    font-size: 16px;
    font-weight: bold;
    color: #fff;
}

.el-button {
    font-size: 16px;
    color: #fff;
}

.el-button:hover {
    color: #1abc9c;
}
</style>
